<template>
  <div id="scene"></div>
</template>

<script>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

let scene; //场景
let camera; //相机
let renderer; //创建渲染器
let controls; //控制器
export default {
  name: "Scene",
  data() {
    return {};
  },
  mounted() {
    this.init();
    this.createControls();
    this.render();
  },
  methods: {
    init() {
      //创建场景
      scene = new THREE.Scene();
      //天空盒
      const textureCube = new THREE.CubeTextureLoader().load([
        "/img/1.jpg",
        "/img/2.jpg",
        "/img/3.jpg",
        "/img/4.jpg",
        "/img/5.jpg",
        "/img/6.jpg",
      ]);
      scene.background = textureCube; // 作为背景贴图
      /**
       * 透视投影相机设置
       */
      const container = document.getElementById("scene");
      /** 透视投影相机对象 */
      camera = new THREE.PerspectiveCamera(
        60,
        container.clientWidth / container.clientHeight,
        1,
        100000
      );
      camera.position.set(600, 90, 600); // 树上面观察
      camera.lookAt(scene.position); // 设置相机方向(指向的场景对象)
      // 创建渲染器对象
      renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(container.clientWidth, container.clientHeight); // 设置渲染区域尺寸
      container.appendChild(renderer.domElement); // body元素中插入canvas对象
      //创建点光源和环境光源
      const point = new THREE.PointLight(0xffffff);
      point.position.set(600, 900, 600); // 点光源位置
      scene.add(point); // 点光源添加到场景中
      // 环境光
      const ambient = new THREE.AmbientLight(0x404040, 1);
      scene.add(ambient);
    },
    createControls() {
      controls = new OrbitControls(camera, renderer.domElement);
    },
    render() {
      renderer.render(scene, camera);
      requestAnimationFrame(this.render); // 请求再次执行渲染函数render
    },
    onDocumentMouseDown(event) {
      event.preventDefault();
      const vector = new THREE.Vector3(); // 三维坐标对象
      vector.set(
        (event.clientX / window.innerWidth) * 2 - 1,
        -(event.clientY / window.innerHeight) * 2 + 1,
        0.5
      );
      vector.unproject(camera);
      const raycaster = new THREE.Raycaster(
        camera.position,
        vector.sub(camera.position).normalize()
      );
      const intersects = raycaster.intersectObjects(scene.children);
      if (intersects.length > 0) {
        const selected = intersects[0]; // 取第一个物体
        console.log(`x坐标:${selected.point.x}`);
        console.log(`y坐标:${selected.point.y}`);
        console.log(`z坐标:${selected.point.z}`);
      }
    },
  },
};
</script>

<style scoped lang="less">
#scene {
  width: 100%;
  height: 100%;
}
</style>
